package com.itheima.filters;

import com.itheima.common.constants.SystemConstants;
import com.itheima.common.util.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @version 1.0
 * @description 说明
 * @package com.itheima.filters
 */
@Component
@Slf4j
//@Order(0)
public class AdminAuthorizeFilter implements GlobalFilter,Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 请求对象
        ServerHttpRequest req = exchange.getRequest();
        // 过滤白名单
        String requestPath = req.getURI().getPath();
        log.info("请求了地址: {}", requestPath);
        // 是否为登录请求
        if (requestPath.startsWith("/admin/login")) {
            return chain.filter(exchange);
        }
        // 响应对象
        ServerHttpResponse res = exchange.getResponse();
        //  1. 获取请求头中token
        String token = req.getHeaders().getFirst("token");
        //  2. 有token
        if(StringUtils.isNotEmpty(token)){
        //  3. 校验token有效性
            int result = AppJwtUtil.verifyToken(token);
            //  4. 有效则放行
            if (SystemConstants.JWT_OK==result) {
                return chain.filter(exchange);
            }
        }
        //  5. 没有放行则，返回401
        res.setStatusCode(HttpStatus.UNAUTHORIZED);
        // 结束，阻止
        return res.setComplete();
    }


    @Override
    public int getOrder() {
        return 0;
    }
}
